
const webResult = require("../web-result");
const router = require("express").Router();
const minIO = require("../min-io");
const hash = require('object-hash');


// 图片路径
const imagesPath = "/resource/images";

async function uploadBase64ImageHandler(request, response) {
    let { data } = request.body;
    if (!data || typeof data !== "string")
    {
        response.send(webResult.failed(undefined, "data type is wrong"));
        return;
    }

    const result = /data:image\/([^;]*);base64,/.exec(data);
    if (!result)
    {
        response.send(webResult.failed(undefined, "format is wrong"));
        return;
    }

    // 去掉 data:image/(png/jpeg/gif/...);base64
    data = data.replace(result[0], "");
    const format = result[1];
    const fileName = hash(data) + "." + format;
    const mime = `images/${format}`;
    const picBuffer = Buffer.from(data, "base64");

    minIO.put(`images/${fileName}`, picBuffer, mime)
    .then(_uploadInfo => {
        response.send(webResult.success(`${imagesPath}/${fileName}`));
    })
    .catch(e => {
        // 有一定可能是，服务器不支持 IPV6
        response.send(webResult.failed(undefined, "服务器内部错误"));
    });
};
router.post("/upload/base64/img", uploadBase64ImageHandler);
router.post("/upload/base64/image", uploadBase64ImageHandler);

module.exports = router;


